import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link ,browserHistory} from 'react-router';
import request from 'superagent';
import $ from 'jquery';
import api from '../api';
import moment from 'moment';
import {bind_change} from '../common/State';

import {Modal,Icon,message,Table,Dropdown,Menu,Row,Col,Button,Input,InputNumber,Form ,Select,Switch,Upload, DatePicker,Checkbox,Popconfirm} from 'antd';
import NavBar from '../common/NavBar';
import Alert from '../common/Alert';
import ContentBody from '../common/ContentBody';
import CommunityChooser from '../common/CommunityChooser';

const Option = Select.Option;
const InputGroup = Input.Group;
const RangePicker = DatePicker.RangePicker;
const CheckboxGroup = Checkbox.Group;

//导入常量
import cities from '../constants/cities';
import {CARD_TYPE, BELONG_TYPE,USER_TYPE} from '../constants/index';

var ModalInfoForm = Form.create()(CommunityChooser);

class UpdateCardForm extends React.Component {
  constructor(props, context){
      super(props, context);
      // let {source} = props.location.query||{};
      this.state={
          constractInfo:[],
          options:[],
          source:'',
          allCheckedList:[],//所有的id
          currentCheckedList:[],
          checkAll:false,


          currentAllCheckedList:[],
          isCheckAllList:[],
      };
  }

  componentWillMount(){
    const {record,constractInfo,currentCheckedList,checkAll,options,allCheckedList,source} = this.props;
    this.setState({
      record,
      constractInfo,
      currentCheckedList,
      checkAll,
      options,
      allCheckedList,
      source
    })


  }

  componentDidMount(){

  }

  refresh(){
    const {record,constractInfo,currentCheckedList,checkAll,options,allCheckedList,source} = this.props;
    this.setState({
      record,
      constractInfo,
      currentCheckedList,
      checkAll,
      options,
      allCheckedList,
      source
    })
  }

 

  //保存事件
  btnSaveClick(event){
    const {validateFieldsAndScroll, setFields} = this.props.form;
    let {record,currentCheckedList,source} = this.state;
    const {self} = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) {
        return;
      }

      // console.log("record=================before",record);
      record = {...record,...values};
      record.constractIds = currentCheckedList;
      record.rangeDate = "";
      if (source == "user") {//业主
        record.userType = '0';
      }else{
        record.userType = '1';
      }

      self.save(record);
      
      
    })
  }

  deleteCard(){
    let {record} = this.state;
    const {self} = this.props;
    self.deleteCard(record);
  }
  

  onChange(date, dateString){
    var{record} = this.state;
    record.beginDate = dateString[0];
    record.endDate = dateString[1];
    this.setState({
      record,
    })
  }


  onSelectCardType(value){
    var {record} = this.state;
    record.cardType = value;
    this.setState({
      record,
    })
  }

  onSelectBelongTo(value){
    var {record} = this.state;
    record.belong2Type = value;
    this.setState({
      record,
    })
  }


  //勾选单个按钮
  onSelectConstract(record,checkedValues){
    
    let {constractInfo,self,currentCheckedList,checkAll,allCheckedList} = this.state;

    currentCheckedList.splice(0,currentCheckedList.length);
    for (var i = 0; i < checkedValues.length; i++) {
      currentCheckedList.push(checkedValues[i]);
    }
    if (checkedValues.length == allCheckedList.length) {//全选了
      checkAll = true;
    }else{//非全选了
      checkAll = false;
    }
    
    this.setState({
      currentCheckedList,
      checkAll,
    })
  }

  //勾选全选button
  onChangeAllCheckBox(e){

    let {constractInfo,self,currentCheckedList,checkAll,allCheckedList} = this.state;
    checkAll = e.target.checked;
    
    currentCheckedList.splice(0,currentCheckedList.length);
    if (e.target.checked) {
      var check = [];
      allCheckedList.map((id,i) =>{
        currentCheckedList.push(id);
      })
    }else{
      allCheckedList.map((id,i) =>{
        currentCheckedList.splice(0,currentCheckedList.length);
      })
    }

    
    this.setState({
      checkAll,
      currentCheckedList,
    })
  }

  render() {
    var {
      source,
      options,
      allCheckedList,

      currentAllCheckedList,
      isCheckAllList,
      record,constractInfo,self,currentCheckedList,checkAll
    } = this.state;
    const { getFieldDecorator,setFieldsValue} = this.props.form;
    const dateFormat = 'YYYY-MM-DD';
    // const {record,constractInfo,self,currentCheckedList,checkAll} = this.props;

    return (

                
          <div style={{border:'1px solid #ddd',padding:20,paddingBottom:0,marginBottom:20,position:'relative'}}>
            <form>

              <Row>
                    <Form.Item
                      label="门卡类型"
                    >
                      {getFieldDecorator('cardType', {
                        rules: [
                          {
                            required: true,
                            message: '请输入门卡类型',
                          },
                        ],
                        initialValue: record && record.cardType ? record.cardType : ''
                    })(<Select 
                          style={{ width: '100%' }} 
                          onChange={this.onSelectCardType.bind(this)}
                        >
                        <Option  value="">请选择</Option>
                        <Option  value="id">身份证</Option>
                        <Option  value="ic">IC卡</Option>
                        <Option  value="nfc">NFC卡</Option>
                        <Option  value="other">其他</Option>
                      {/*{
                        Object.keys(CARD_TYPE).map((key,index) =>{
                          return <Option key={index} value={key}>{CARD_TYPE[key]}</Option>
                        })
                      }*/}
                    </Select>)}
                    </Form.Item>
              </Row>
              {/*<Row>
                    <Form.Item
                      label="使用者身份"
                    >
                      {getFieldDecorator('userType', {
                        rules: [
                          {
                            required: true,
                            message: '请输入门卡类型',
                          },
                        ],
                        initialValue: (record && record.userType) || (record && record.userType == 0) ? `${record.userType}` : ''
                    })(<Select 
                          style={{ width: '100%' }} 
                        >
                        <Option  value="">请选择</Option>
                      {
                        Object.keys(USER_TYPE).map((key,index) =>{
                          return <Option key={index} value={key}>{USER_TYPE[key]}</Option>
                        })
                      }
                    </Select>)}
                    </Form.Item>
              </Row>*/}
              <Row>
                    <Form.Item
                      label="门卡卡号"
                    >
                      {getFieldDecorator('cardNumber', {
                        rules: [
                          {
                            required: true,
                            message: '请输入门卡卡号',
                          },
                        ],
                        initialValue: record && record.cardNumber ? `${record.cardNumber}` : ''
                    })(<Input size="large" placeholder="请输入门卡卡号" />)}
                    </Form.Item>
              </Row>
              <Row>
                    <Form.Item
                      label="门卡有效日期"
                    >
                      {getFieldDecorator('rangeDate', {
                        rules: [
                          {
                            required: true,
                            message: '请输入门卡有效日期',
                          },
                        ],
                        initialValue: record && record.beginDate && record.endDate ? 
                                      [moment(`${record.beginDate}`, dateFormat), moment(`${record.endDate}`, dateFormat)] 
                                      : 
                                      ''
                    })(<RangePicker onChange={this.onChange.bind(this)} />)}
                    </Form.Item>
              </Row>
              <Row>
                    <Form.Item
                      label="归属类型"
                    >
                      {getFieldDecorator('belong2Type', {
                        rules: [
                          {
                            required: true,
                            message: '请输入归属类型',
                          },
                        ],
                        initialValue: record && record.belong2Type ? record.belong2Type : ''
                    })(<Select 
                          style={{ width: '100%' }} 
                          onChange={this.onSelectBelongTo.bind(this)}

                        >
                        <Option  value="">请选择归属类型</Option>
                        <Option  value="owner">本人</Option>
                        <Option  value="family_members">家属</Option>
                      {/*{
                        Object.keys(BELONG_TYPE).map((key,index) =>{
                          return <Option key={index} value={key}>{BELONG_TYPE[key]}</Option>
                        })
                      }*/}
                    </Select>)}
                    </Form.Item>
              </Row>

              <Row>
                <Form.Item
                  label="归属人备注"
                >
                  {getFieldDecorator('belong2Remark', {
                    rules: [
                      {
                        required: true,
                        message: '请输入归属人备注',
                      },
                    ],
                    initialValue: record && record.belong2Remark ? `${record.belong2Remark}` : ''
                })(
                  <Input type='text' style={{width:'100%'}} placeholder="备注" />
                  )}
                </Form.Item>
              </Row>

              <Row>
                <Form.Item
                  label="门口机权限"
                >
                  {getFieldDecorator('constractIds', {
                    rules: [
                      {
                        required: true,
                        message: '请勾选权限',
                      },
                    ],
                    initialValue: ['']
                })(
                <div>
                  <CheckboxGroup options={options} onChange={this.onSelectConstract.bind(this,record)} value={currentCheckedList}/>
                  <Checkbox 
                      checked = {checkAll}
                      value = 'all'
                      onChange={this.onChangeAllCheckBox.bind(this)}>全选</Checkbox>
                </div>
                  )}
                </Form.Item>
              </Row>

          </form>

          <div className="text-center marginB20">
              <Button
                type='primary'
                onClick={this.btnSaveClick.bind(this)}
              >
                修改
              </Button>
              <Popconfirm 
                title="确定要删除?" 
                onConfirm={this.deleteCard.bind(this)} 
                okText="确定" 
                cancelText="取消"
              >
                <Button
                    type='default'
                    style={{marginLeft:"20px"}}
                >
                    删除
                </Button>
              </Popconfirm>
           </div>
          </div>
    );
  }
}

UpdateCardForm.contextTypes= { router: React.PropTypes.object.isRequired};

export default Form.create()(UpdateCardForm);
